import importlib
import requests, os, cv2, sys, io, threading, traceback
import numpy as np
from multiprocessing.dummy import Pool as ProcessPool


def dynamic_import(class_name, module_name):
    try:
        module = importlib.import_module(module_name)
        if hasattr(module, class_name):
            return getattr(module, class_name)
        else:
            raise AttributeError(f"Class '{class_name}' not found in module '{module_name}'")
    except ImportError:
        raise ImportError(f"Module '{module_name}' not found")

def down(image_ftp_path):
    try:
        assert isinstance(image_ftp_path, str)
        response = requests.get(url=image_ftp_path,verify=False, timeout=5)
        image = np.asarray(bytearray(response.content), dtype=np.uint8)
        image = cv2.imdecode(image, cv2.IMREAD_COLOR)
        return True, image, image_ftp_path
    except Exception as e:
        return False, None, image_ftp_path
    

def download_imgs(image_ftp_paths):
    """多进程下载图片到内存, 注意由于是多进程, 所以logging不互通
    """
    # 没有参数时默认是 cpu 的核心数
    pool = ProcessPool()
    results = pool.map(down, image_ftp_paths)
    pool.close()
    pool.join()
    images = [result[1] for result in results]
    ret = True
    for img in images:
        if img is None:
            ret = False
    return ret, images